﻿using Microsoft.Web.WebView2.Wpf;
using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ShanNiang.Packing.Behaviors
{
    public  class WebView2Behavior: Behavior<WebView2>
    {
        public static readonly DependencyProperty NavigateUrlProperty =
        DependencyProperty.RegisterAttached("NavigateUrl", typeof(string), typeof(WebView2Behavior),
            new PropertyMetadata(null, OnNavigateUrlChanged));



        public static void SetNavigateUrl(WebView2 element, string value) =>
            element.SetValue(NavigateUrlProperty, value);

        /// <summary>
        /// 导航路径
        /// </summary>
        public string NavigateUrl
        {
            get => (string)GetValue(NavigateUrlProperty);
            set => SetValue(NavigateUrlProperty, value);
        }


        // 其他Get/Set方法...

        private static async void OnNavigateUrlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is WebView2 webView && e.NewValue is string url)
            {
                // 确保控件已加载到可视化树
                if (!webView.IsLoaded)
                {
                    //webView.Loaded += async (sender, _) =>
                    //    await TryNavigateAsync(webView, url);
                }
                else
                {
                    await TryNavigateAsync(webView, url);
                }
            }
        }

        private static async Task TryNavigateAsync(WebView2 webView, string url)
        {
            if (webView.CoreWebView2 == null)
            {
                // 延迟初始化
                await webView.EnsureCoreWebView2Async();
            }
            if (webView.CoreWebView2 != null)
            {
                webView.CoreWebView2.Navigate(url);
            }
        }
    }
}
